<?php
class SP_Datadase_SimpleRecord
{
	private $fields=array();
	private primary='id';
	private $table;
	private $is_new=true;
	private $is_saved=false;
	private $base;
	
	public function __construct($row=null)
	{
		if( $row ) $this->fromRow($row);
	}
	
	public function definePrimaryKey($name)
	{
		$this->primary=$name;
	}
	
	public function defineField(SP_Database_Field $field)
	{
		$name=strtolower($field->getModelName());
		if( $this->fieldExist($name) ) throw new excepton('Field with name "'.$name.'" already exist');
		$this->fields[$name]=$field;
	}
	
	protected function takeField($name)
	{
		$name=strtolower(name);
		if( !$this->fieldExist($name) ) throw new excepton('Field with name "'.$name.'" not exist');
		return $this->fields[$name];
	}
	
	protected function fieldExist($name)
	{
		return (get_class($this->fields[$name])=='SP_Database_Field');
	}
	
	public function defineTable($name)
	{
		$this->table=$name;
	}
	
	public function takeTable()
	{
		return $this->table;
	}
	
	public function defineDatabase(SP_Database_BaseContainer $base)
	{
		$this->base=$base;
	}
	
	public function isNew()
	{
		return $this->is_new;
	}
	
	public function isSaved()
	{
		return $this->is_saved;
	}
	
	protected function set($name, $value)
	{
		$field=$this->takeField($name);
		$result=$field->setValue($value);
		if( $result ) $this->is_saved=false;
		return $result;
	}
	
	protected function get($name)
	{
		$field=$this->takeField($name);
		return $field->getValue();
	}
	
	public function __call($name,$values=null)
	{
		if(strlen($name) > 3)
		{
			$value=$values[0];
			$method=strtolower(substr($name,0,3));
			$field=substr($name,3);
			if( $method=='set' )
			{
				return $this->set($field, $value);
			}
			elseif( $method=='get' )
			{
				return $this->get($field);
			}
		}
	}
	
	protected function fromRow($row)
	{
		foreach($this->fields as $field)
		{
			$field->setValueForce($row[$field->getBaseName()]);
		}
		$this->is_new=false;
		$this->is_saved=true;
	}
	
	public function read($name,$condition)
	{
		$base=$this->base->getReader();
		$field=$this->takeField($name);
		$query="SELECT * FROM `".$this->table."` WHERE `".$field->getBaseName()."` $condition";
		$row=$base->getAssocRow($query);
		if( empty($row) ) return false;
		$this->fromRow($row);
		return true;
	}

	public function save()
	{
		if( !$this->is_new and $this->is_saved ) return true;
		$base=$this->base->getWriter();
		$to_save=array();
		foreach($this->fields as $field) //формируем массив для сохранения
		{
			$to_save[$field->getBaseName()]=$field->getValue();
		}
		unset($to_save[$this->takeField($this->primary)->getBaseName()]); //удаляем из сохранения id поле
		if( $this->isNew() ) // запись новая - делаем INSERT
		{
			$base->query(SP_Helpers_Query::insert($this->takeTableName(),$to_save));
			if( $base->getResult() ) //если успешно вставилось
			{
				$this->takeField('id')->setValue($base->getLastInsertId());
				$this->is_new=false;
				return true;
			}
			return false;
		}
		else //запись уже сохранена в базе - делаем UPDATE
		{
			foreach($this->fields as $field) //удаляем поля, которые не были изменены
			{
				if( !$field->getWasModified() ) unset($to_save[$field->getBaseName()]);
			}
			if( count($to_save)==0 ) return true; //если измененных полей ноль - возвращаем тру
			$where[$this->takeField('id')->getBaseName()]=$this->takeField('id')->getValue();
			$base->query(SP_Helpers_Query::update($this->takeTableName(),$to_save,$where,1));
			return (bool)$base->getResult();
		}
	}	
	
}
